<?php

App::uses('Controller', 'Controller');
App::uses('Klass',      'Lib');
App::uses('Mailer',     'Lib');

class AppController extends Controller {
    
    public $pageTitle;
    public $settings;
    
    public $components = array(
        'Session',
        'Auth' => array(
            'loginAction'  => '/app/login',
            ''
        )
    );
    
    public function beforeFilter() {
        // is Admin?
        if (! preg_match('/^admin\./', env('SERVER_NAME'))) {
            $this->Auth->allow();
        } else {
            $this->Auth->allow(array('forgot_password', 'change_password'));
            $this->set('isAdmin', true);
        }
        
        // load Settings
        if (! $this->Settings) {
            $this->loadModel('Settings');
        }
        $data = $this->Settings->find('list', array(
                'fields' => array('key', 'value')
        ));
        $this->settings = new Klass($data);
        $this->set('Settings', $this->settings);
    }
    
    public function beforeRender() {
        // Page Title
        if (! empty($this->pageTitle)) {
            $this->set('title_for_layout', $this->pageTitle);
        }
    }
    
    public function login() {
        $this->layout = 'login';
        
        if ($this->request->isPost()) {
            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirectUrl());
            }
            
            $this->setFlash(__('Prijava nije uspela'));
        }
    }
    
    public function logout() {
        $this->redirect($this->Auth->logout());
    }
    
    public function setFlash($message, $type='error') {
        $this->Session->setFlash($message, 'flash', array('type' => $type));
    }
    
    public function forgot_password() {
        $this->layout = 'login';
        
        if ($this->request->isPost()) {
            $this->loadModel('User');
            $email = @$this->data['User']['email'];
            $this->set('email', $email);
            $user = $this->User->findByEmail($email);
            
            if (empty($user)) {
                $this->setFlash(__('Ne postoji korisnik za zadatu email adresu.'));
            } else {
                $hash = md5(date('Y-m-d H:i:s'));
                $user['User']['change_password_hash'] = $hash;
                $user['User']['change_password_ts'] = time() + CHANGE_PASSWORD_LIFETIME;
                $this->User->save($user);
                
                $to      = $user['User']['email'];
                $subject = $this->settings->name . ': ' . __('Promena lozinke');
                $body    = $this->parseView('/App/change_password_email', array(
                    'user'     => $user,
                    'settings' => $this->settings
                ));
                Mailer::send($to, $subject, $body);
                $this->setFlash(__('Link za promenu lozinke je poslat na navedenu adresu.'), 'ok');
            }
        }
    }
    
    protected function parseView($view, $data=array()) {
        $View = new View($this);
        foreach ($data as $k=>$v) {
            $View->set($k, $v);
        }
        return $View->render($view, false);
    }
    
    public function change_password($hash=null) {
        $this->layout = 'login';
        
        if (! empty($hash)) {
            $this->set('change_password_hash', $hash);
            $this->loadModel('User');
            $user = $this->User->find('first', array(
                'conditions' => array(
                    'change_password_hash'  => $hash,
                    'change_password_ts >=' => time() - CHANGE_PASSWORD_LIFETIME
                )
            ));
            
            if (! empty($user)) {
                if ($this->request->isPost()) {
                    $data = $this->data;
                    $pass1 = trim(@$data['User']['password1']);
                    $pass2 = trim(@$data['User']['password2']);
                    
                    if (strlen($pass1)<PASSWORD_MIN_LENGTH) {
                        $this->setFlash(sprintf(__('Minimalna dužina lozinke je %d karaktera'), 
                                        PASSWORD_MIN_LENGTH));
                    } else if($pass1 != $pass2) {
                        $this->setFlash(__('Unete lozinke se ne podudaraju'));
                    } else {
                        $user['User']['password'] = $this->Auth->password($pass1);
                        $user['User']['change_password_hash'] = null;
                        $user['User']['change_password_ts']   = null;
                        
                        $this->setFlash(__('Lozinka je promenjena.'), 'ok');
                        $this->User->save($user);
                        $this->redirect('/');
                    }
                }
                
                return $this->render();
            }
        }
        
        $this->redirect('/');
    }
    
}
